#pragma ocne
#include <iostream>
#include <memory>
#include "log.hpp"
#include "Epoll.hpp"
#include "Socket.hpp"

static const uint16_t port = 8000;
uint32_t EVENT_IN = (EPOLLIN);
uint32_t EVENt_OUT = (EPOLLOUT);

class EpollServer :public nocopy
{
    static const int num = 64;

public:
    EpollServer()
        : _listensocket_ptr(new Sock()), _epoll_ptr(new Epoll())
    {
    }

    void Init()
    {
        _listensocket_ptr->Socket();
        int opt = 1;
        setsockopt(_listensocket_ptr->Fd(), SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt));
        _listensocket_ptr->Bind(port);
        _listensocket_ptr->Listen();
    }

    void Accepter()
    {
        // 获取新链接
        std::string ip;
        uint16_t port = 0;
        int sock = _listensocket_ptr->Accept(&ip, &port);
        if (sock > 0)
        {
            // 不能直接取，需要注册
            _epoll_ptr->EpollUpdate(EPOLL_CTL_ADD, sock, EVENT_IN);
            lg.logmessage(info, "get a new link,client@%s:%d", ip.c_str(), port);
        }
    }

    void Recver(int fd)
    {
        char buff[1024];
        ssize_t n = read(fd, buff, sizeof(buff) - 1);
        if (n > 0)
        {
            buff[n] = 0;
            std::cout << "get a message:" << buff << std::endl;
            // 回显
            std::string echo_str = "server echo$:";
            echo_str += buff;
            write(fd, echo_str.c_str(), echo_str.size());
        }
        else if (n == 0)
        {
            lg.logmessage(info, "client quit, me too, close fd:%d", fd);
            // 先取消关注，再关文件
            _epoll_ptr->EpollUpdate(EPOLL_CTL_DEL, fd, 0);
            close(fd);
        }
        else
        {
            lg.logmessage(warning, "recv error fd:%d", fd);
            _epoll_ptr->EpollUpdate(EPOLL_CTL_DEL, fd, 0);
            close(fd);
        }
    }

    void Dispatcher(struct epoll_event rev[], int num)
    {
        for (int i = 0; i < num; i++)
        {
            uint32_t events = rev[i].events;
            int fd = rev[i].data.fd;

            if (events & EVENT_IN)
            {
                if (fd == _listensocket_ptr->Fd())
                {
                    Accepter();
                }
                else
                {
                    Recver(fd);
                }
            }
            else if (events & EVENt_OUT)
            {
            }
            else
            {
            }
        }
    }

    void Start()
    {
        // 将listensock添加到epoll中 -> listensock和他关心的事件,添加到内核epoll模型中rb_tree
        _epoll_ptr->EpollUpdate(EPOLL_CTL_ADD, _listensocket_ptr->Fd(), EVENT_IN);
        struct epoll_event revs[num];

        for (;;)
        {
            int n = _epoll_ptr->EpollWait(revs, num);
            if (n > 0)
            {
                lg.logmessage(info, "event happened,fd:%d", revs[0].data.fd);
                Dispatcher(revs, n);
            }
            else if (n == 0)
            {
                lg.logmessage(info, "timeout...");
            }
            else
            {
                lg.logmessage(ERROR, "epoll wait error");
            }
        }
    }

private:
    std::unique_ptr<Sock> _listensocket_ptr;
    std::unique_ptr<Epoll> _epoll_ptr;
};